﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using ZilLion.Service.TaskPlatform.Domain.Respository.Interface;

namespace ZilLion.Service.TaskPlatform.Domain.Respository.GridFs
{
    public class LocalTaskPackageRepository : ITaskPackageRespository
    {
        private readonly DirectoryInfo _rootpath;

        public LocalTaskPackageRepository()
        {
            _rootpath = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskLocalFiles"));
            if (!_rootpath.Exists)
                _rootpath.Create();
        }

        public byte[] GetPackageBytes(string packageKey)
        {
            var filepath = Path.Combine(_rootpath.FullName, packageKey);

            if (File.Exists(filepath))
                return File.ReadAllBytes(filepath);
            return null;
        }

        public string UploadFileToGridFs(Stream fileStream, string packageKey)
        {
            var filepath = Path.Combine(_rootpath.FullName, packageKey);
            if (File.Exists(filepath))
                File.Delete(filepath);
            var byteArray = fileStream.ToByteArray();
            File.WriteAllBytes(filepath, byteArray);
            MD5 md5 = new MD5CryptoServiceProvider();
            var retVal = md5.ComputeHash(byteArray);
            var sb = new StringBuilder();
            foreach (var t in retVal)
                sb.Append(t.ToString("x2"));
            return sb.ToString().ToUpper();
        }
    }
}